package com.sips.rms.daos;

import com.sips.rms.entities.DatabaseEntity;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public abstract class AbstractDatabaseEntityDao<T extends DatabaseEntity> {

    @Autowired
    protected SessionFactory sessionFactory;

    private Class<T> persistentClass = null;

    public AbstractDatabaseEntityDao(Class<T> persistentClass) {
        this.persistentClass = persistentClass;
    }


    public T update(T entity) {
        getSessionFactory().getCurrentSession().update(entity);
        return (T) entity;
    }


    public long save(T entity) {
        Long id = (Long) getSessionFactory().getCurrentSession().save(entity);
        return id.longValue();
    }


    public T fetch(long id) {
        return (T) getSessionFactory().getCurrentSession().get(persistentClass, id);
    }


    public void delete(T entity) {
        getSessionFactory().getCurrentSession().delete(entity);
    }


    public T load(long id) {
        return (T) getSessionFactory().getCurrentSession()
                .load(persistentClass, id);
    }


    public Class<T> getPersistentClass() {
        return persistentClass;
    }


    public T insert(T entity) {
        Long newId = (Long) getSessionFactory().getCurrentSession().save(entity);
        entity.setId(newId);
        return entity;
    }


    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }


    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}
